

#include "../include/client.h"

/*线程状态
PTHREAD_CREATE_DETACHED:分离状态
PTHREAD_CREATE_JOINABLE:默认可会合状态
*/
#define PTHREAD_STATE	PTHREAD_CREATE_DETACHED 
#define STACK_SIZE	120*1024

/*int main(int argc,char **argv)
  {
  int					re_val = 0;//函数返回值
  pthread_attr_t		pthread_attr;
  pthread_args_t		pthread_args;

//线程初始化
re_val = pthread_init(&pthread_attr,&pthread_args);
if(0 != re_val)
{
printf("初始化线程失败!\n");
exit(0);
}
printf("线程初始化成功!\n");

//销毁结构体
re_val = pthread_attr_destroy(&pthread_attr);
if(0 != re_val)
{
printf("销毁线程结构体失败:%s\n",strerror(errno));
exit(0);
}
re_val = pthread_mutex_destroy(&pthread_args.lock);
if(0 != re_val)
{
printf("销毁锁结构失败:%s\n",strerror(errno));
exit(0);
}

return 0;
}
*/

int thread_start(pthread_t * thread_id, THREAD_BODY * thread_workbody,  void *pthread_args)
{
	pthread_attr_t          pthread_attr;//线程属性

	int			 re_val = -1;


	re_val = pthread_init(&pthread_attr);
	if(0 > re_val)
	{
		 pthread_attr_destroy(&pthread_attr);
        return re_val;
	}


	if( pthread_create(thread_id, &pthread_attr, thread_workbody, pthread_args))
	{
		printf("Create thread failure: %s\n", strerror(errno));
		pthread_attr_destroy(&pthread_attr);
        return re_val;
	}
	
    return 0;
}


/*功能：多线程初始化
 *参数：pthread_attr:线程属性；pthread_args:线程参数
 *返回：成功返回0，失败返回-1
 */

int pthread_init(pthread_attr_t *pthread_attr)
{
	int					re_val = 0;

	//线程初始化
	re_val = pthread_attr_init(pthread_attr);
	if(0 != re_val)
	{
		printf("初始化线程属性失败!:%s\n",strerror(errno));
		goto Cleanup;
	}

/*
	//获取当前的线程栈大小
	re_val = pthread_attr_getstacksize(pthread_attr, &stack_size);
	if(0 != re_val)
	{
		printf("获取堆栈大小失败!:%s\n",strerror(errno));
		goto Cleanup;
	}
	//打印堆栈值
	printf("stack_size = %dB, %dk\n",(int)stack_size,(int)(stack_size/1024));

*/
	//设置堆栈大小
	re_val = pthread_attr_setstacksize(pthread_attr,STACK_SIZE);
	if(0 != re_val)
	{
		printf("设置堆栈大小失败!:%s\n",strerror(errno));
		goto Cleanup;
	}

	//设置线程为分离状态
	re_val = pthread_attr_setdetachstate(pthread_attr,PTHREAD_STATE);
	if(0 != re_val)
	{
		printf("设置线程状态失败!:%s\n",strerror(errno));
		goto Cleanup;
	}
	return 0;
Cleanup:
	pthread_attr_destroy(pthread_attr);
	return -1;
}



